package com.zzf.concurrent.example.communication;

import com.zzf.concurrent.example.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author GaoFeng2017
 * @date 2019/8/6 10:26
 */

@Slf4j
public class ProducerConsumerV1 {

    private volatile int index = 1;

    private final Object LOCK = new Object();

    public static void main(String[] args) {

        /* 由于produce和consume不存在通信，所以可能会出现多次消费为index不变的情况，甚至是消费跳过的情况。
         * 当生产者则生产完成后，需要主动通知消费者去消费，我们可以使用wait/notify来实现
         */
        ProducerConsumerV1 pc = new ProducerConsumerV1();
        new Thread() {
            @Override
            public void run() {
                pc.produce();
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                pc.consume();
            }
        }.start();

    }

    public void produce() {
        while (true) {
            synchronized (LOCK) {
                log.info("{}开始生产 -> {}", Thread.currentThread().getName(), ++index);
            }

            TimeUtil.sleep(1);
        }
    }

    public void consume() {
        while (true) {
            synchronized (LOCK) {
                log.info("{}开始消费 -> {}", Thread.currentThread().getName(), index);
            }
            TimeUtil.sleep(1);
        }
    }
}
